module spi_master(
    input  clk,
    input  rst_n,
    output reg sclk,
    output reg ss_n,
    output reg mosi,
    input  miso
);
    
    reg clken, clkr;
    reg [1:0] clks;
    reg [7:0] dreg, dbuf;
    reg [31:0] cnt0, cnt1;
    
    //产生SPI时钟
    always @(posedge clk, negedge rst_n) begin
        if (!rst_n) begin
            clkr <= 1'b0;
            clks <= 2'b0;
            cnt0 <= 32'b0;
        end
        else begin
            clkr <= cnt0[31];
            clks[0] <= (!clkr) & cnt0[31];
            clks[1] <= clkr & (!cnt0[31]);
            cnt0 <= cnt0 + 32'h051EB852;
        end
    end
    
    //数据发送控制
    always @(posedge clk, negedge rst_n) begin
        if (!rst_n) begin
            sclk <= 1'b0;
            ss_n <= 1'b1;
            mosi <= 1'b0;
            clken <= 1'b0;
            dreg <= 8'h6C;
            cnt1 <= 32'b0;
        end
        else begin
            if (clks[1]) cnt1 <= cnt1 + 1'b1;
            if (clks[1]&(cnt1==0))
                clken <= 1'b1;
            else if (clks[1]&(cnt1==8))
                clken <= 1'b0;
            if (clks[1]&(cnt1==0))
                ss_n <= 1'b0;
            else if (clks[0]&(cnt1==9))
                ss_n <= 1'b1;
            sclk <= clken & clkr;
            if (clken&clks[0]) begin
                mosi <= dreg[7];
                dreg <= {dreg[6:0], 1'b0};
            end
            else if (!clken) begin
                mosi <= 1'b0;
            end 
        end
    end
    
    //数据接收控制
    always @(posedge clk, negedge rst_n)
    begin
        if (!rst_n) begin
            dbuf <= 8'b0;
        end
        else begin
            if ((!ss_n)&clks[0]) begin
                dbuf <= {dbuf[6:0], miso};
            end
        end 
    end 
    
endmodule 